package com.rtsapp.server.network.protocol.command;

import com.rtsapp.server.common.ByteBuffer;
import com.rtsapp.server.network.protocol.ProtocolConstants;
import com.rtsapp.server.profiling.NetworkProfilling;
import com.rtsapp.server.utils.RC4Utils;
import io.netty.util.AttributeKey;
import com.rtsapp.server.logger.Logger;

import com.rtsapp.server.common.IByteBuffer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.codec.MessageToByteEncoder;


@Sharable
public class CommandOutHandler  extends MessageToByteEncoder<ICommand>{

	private static final Logger logger =com.rtsapp.server.logger.LoggerFactory.getLogger( CommandOutHandler.class );

	
	@Override
	protected void encode(ChannelHandlerContext ctx, ICommand command, ByteBuf out)
			throws Exception {
	

		try {

			int startIdx = out.writerIndex();
			IByteBuffer buffer = new ByteBuffer(out);

			buffer.writeInt(0);
			command.writeToBuffer(buffer);
			int endIdx = out.writerIndex();
			out.setInt(startIdx, endIdx - startIdx - 4);

			int bytes = (endIdx - startIdx);
			logger.info("[cmd send] id=0x{}, size={} bytes",  Integer.toHexString(command.getCommandId()) ,  bytes );
			NetworkProfilling.getInstance().profillingOutput( bytes );

		}catch( Throwable ex ){
			logger.error("输出编码:" + command + "时出错, 消息序列已经不再正确,关闭用户连接", ex);
			ctx.channel().close();
		}
		
	}
	

}
